/**
 * 
 */
package org.jverify.data.provider;

import java.io.File;
import java.util.List;

import org.jverify.data.pojo.FileData;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.EmbeddedConfiguration;
import com.db4o.query.Predicate;

/**
 * @author imavroukakis
 */
public class Db4oOperations implements DataProvider {

	private static final String DB4O_FILE = "jverify.db4o";
	private final EmbeddedConfiguration conf = Db4oEmbedded.newConfiguration();
	private ObjectContainer dataStore;

	/*
	 * (non-Javadoc)
	 * @see
	 * org.jverify.data.provider.DataProvider#add(org.jverify.data.pojo.FileData
	 * )
	 */
	@Override
	public void store(final FileData fileData) {
		dataStore.store(fileData);
	}

	/*
	 * (non-Javadoc)
	 * @see org.jverify.data.provider.DataProvider#get(java.lang.String)
	 */
	@Override
	public FileData get(final String fullPathName) {
		final List<FileData> fileData = dataStore.query(new Predicate<FileData>() {
			/**
			 * 
			 */
			private static final long serialVersionUID = -5250974601575935305L;

			@Override
			public boolean match(final FileData fd) {
				return fd.getFileName().equals(fullPathName);
			}
		});
		return fileData.get(0);
	}

	/*
	 * (non-Javadoc)
	 * @see org.jverify.data.provider.DataProvider#getAll()
	 */
	@Override
	public List<FileData> getAll() {
		return dataStore.query(FileData.class);
	}

	/*
	 * (non-Javadoc)
	 * @see
	 * org.jverify.data.provider.DataProvider#remove(org.jverify.data.pojo.FileData
	 * )
	 */
	@Override
	public boolean remove(final FileData fileData) {
		final ObjectSet<FileData> result = dataStore.queryByExample(fileData);
		final FileData fdResult = result.next();
		if (fdResult != null) {
			dataStore.delete(fdResult);
			return true;
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * @see
	 * org.jverify.data.provider.DataProvider#update(org.jverify.data.pojo.FileData
	 * )
	 */
	@Override
	public void update(final FileData fileData) {
		// TODO Auto-generated method stub

	}

	@Override
	public void shutdown() {
		if (dataStore != null) {
			dataStore.close();
		}
	}

	@Override
	public void initialise() {
		final File db4oFile = new File(DB4O_FILE);
		if (db4oFile.exists() && !db4oFile.delete()) {
			throw new IllegalStateException();
		}
	}

	@Override
	public void start() {
		dataStore = Db4oEmbedded.openFile(conf, DB4O_FILE);
	}
}
